package com.dao;

import com.beans.OrderGoods;
import com.beans.OrderInfo;
import com.beans.PageInfo;
import com.jdbc.DBUtil;
import com.utils.StrUtil;

import java.text.SimpleDateFormat;
import java.util.List;

public class OrderDao {
    //得到订单个数
    public int getOrderCount(String orderNo, String orderState, String beginDate, String endDate) {
        String sql="select count(*) from orderInfo where 1=1 ";

        if(!StrUtil.isNullOrEmpty(orderNo)){
            sql+=" and  orderNo='"+ orderNo +"'";
        }

        if(!StrUtil.isNullOrEmpty(orderState)){
            sql+=" and  orderState='"+ orderState +"'";
        }

        if(!StrUtil.isNullOrEmpty(beginDate)){
            sql+=" and  orderDate>='"+ beginDate +"'";
        }
        if(!StrUtil.isNullOrEmpty(endDate)){
            sql+=" and  orderDate <='"+ endDate +" 23:59:59'";
        }

        Long result= DBUtil.getScalar(sql);
        return  Integer.parseInt(result+"");  //因为 上面的 getScalar 实际返回的是long型,而方法的返回值是int型,所以要转换一下
    }
    //查询订单列表
    public List<OrderInfo> getOrderList(String orderNo, String orderState, String beginDate, String endDate, PageInfo page) {
        String sql="select * from orderInfo where 1=1 ";

        if(!StrUtil.isNullOrEmpty(orderNo)){
            sql+=" and  orderNo='"+ orderNo +"'";
        }

        if(!StrUtil.isNullOrEmpty(orderState)){
            sql+=" and  orderState='"+ orderState +"'";
        }

        if(!StrUtil.isNullOrEmpty(beginDate)){
            sql+=" and  orderDate >='"+ beginDate +"'";
        }
        if(!StrUtil.isNullOrEmpty(endDate)){
            sql+=" and  orderDate <='"+ endDate +"  23:59:59'";
        }

        sql+=" order by editDate desc limit ?,? ";

        return DBUtil.getList(sql, OrderInfo.class, page.getBeginRow(),page.getPageSize());
    }
    //通过id查询订单
    public OrderInfo getOrderById(int orderId) {
        String sql="select a.*,b.memberNO as memberNO  from orderInfo a left join memberInfo b on a.memberId=b.id  where a.id= ? ";
        return DBUtil.getSingleObject(sql, OrderInfo.class, orderId);
    }
    //通过订单id查询商品
    public List<OrderGoods> getGoodslist(int orderId) {
        String sql="select * from orderGoods where orderId=? ";
        return DBUtil.getList(sql, OrderGoods.class, orderId);
    }
    //发货
    public int sendGoods(int orderId, String state) {
        String sendDate=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new java.util.Date());
        String sql="update orderInfo set orderState=?,sendDate=? where id=? ";
        return DBUtil.update(sql, state,sendDate,orderId);
    }
    //删除订单
    public void deleteOrder(int orderId) {
        //先删除除该订单对应的商品
        DBUtil.update("delete from orderGoods where orderId=?", orderId);

        //再删除订单表
        DBUtil.update("delete from orderInfo where id=?", orderId);
    }
}
